package com.rdc.qingkou.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.constraint.ConstraintLayout;
import android.support.v4.view.ViewPager;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Toast;

import com.githang.statusbar.StatusBarCompat;
import com.rdc.qingkou.Application.MyApplication;
import com.rdc.qingkou.R;
import com.rdc.qingkou.adapter.MyFragmentStatePagerAdapter;
import com.rdc.qingkou.base.BaseActivity;
import com.rdc.qingkou.config.Constant;
import com.rdc.qingkou.config.URL;
import com.rdc.qingkou.presenter.BrowsePresenter;
import com.rdc.qingkou.ui.iview.IBrowseView;
import com.rdc.qingkou.utils.MyUtils;
import com.rdc.qingkou.view.fragment.BrowseFragment;
import com.rdc.qingkou.vo.CardAndUserVO;
import com.rdc.qingkou.vo.CardVO;
import com.rdc.qingkou.vo.UserVO;
import com.rdc.qingkou.widget.GalleryPageTransformer;
import com.rdc.qingkou.widget.MyViewPager;

import java.util.ArrayList;
import java.util.List;

import cn.jzvd.JZVideoPlayer;


public class BrowseActivity extends BaseActivity<BrowsePresenter> implements IBrowseView, View.OnClickListener {

    private MyViewPager viewPager;
    private List<BrowseFragment> mBrowseFragmentList = new ArrayList<>();
    private MyFragmentStatePagerAdapter<BrowseFragment> mAdapter;
    private int mCurrentPage = 1;
    private boolean isLastPage = false;//服务器端卡片到最后一页
    private boolean isUpdate = false;//正在联网更新卡片
    private Intent mIntent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MyApplication.addActivity(this);
        StatusBarCompat.setStatusBarColor(this, getResources().getColor(R.color.windowBackground), true);
        setContentView(R.layout.activity_browse);
        initView();
        mIntent = getIntent();
        getCards();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case 1:
                if (resultCode == BrowseDetailActivity.DELETED) {
                    int deletedCardId = data.getIntExtra("deletedCardId", 0);
                    for (int i = 0; i < mBrowseFragmentList.size(); i++) {
                        CardAndUserVO cardAndUserVO = mBrowseFragmentList.get(i).getCard();
                        if (cardAndUserVO.getCardVO().getCardId() == deletedCardId) {
                            mBrowseFragmentList.remove(i);
                            mAdapter.notifyDataSetChanged(true);
                            break;
                        }
                    }
                }
                break;
        }
    }

    private void getCards() {
        String tag = mIntent.getStringExtra("tag");
        if (tag != null) {
            if (MyUtils.isNetworkConnected(this)) {
                mPresenter.getCardByTag(tag, mCurrentPage);
            } else {
                Toast.makeText(this, "无网络！", Toast.LENGTH_SHORT).show();
            }
        } else if (mIntent.getIntExtra("collect", 0) == 1) {
            if (MyUtils.isNetworkConnected(this)) {
                mPresenter.getCardByKey(MyApplication.getUser().getUserId(), mCurrentPage, URL.GET_CARD_BY_COLLECTED);
            } else {
                Toast.makeText(this, "无网络！", Toast.LENGTH_SHORT).show();
            }
        } else if (mIntent.getIntExtra("appreciate", 0) == 1) {
            if (MyUtils.isNetworkConnected(this)) {
                mPresenter.getCardByKey(MyApplication.getUser().getUserId(), mCurrentPage, URL.GET_CARD_BY_APPRECIATED);
            } else {
                Toast.makeText(this, "无网络！", Toast.LENGTH_SHORT).show();
            }
        }
    }


    private void initView() {
        ConstraintLayout mRootLayout = (ConstraintLayout) findViewById(R.id.browse_layout);
        mRootLayout.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                return viewPager.dispatchTouchEvent(motionEvent);
            }
        });

        viewPager = (MyViewPager) findViewById(R.id.browse_viewpager);
        mAdapter = new MyFragmentStatePagerAdapter<>(getSupportFragmentManager(), mBrowseFragmentList);
        viewPager.setAdapter(mAdapter);
        viewPager.setOffscreenPageLimit(3);
        viewPager.setPageTransformer(false, new GalleryPageTransformer());
        viewPager.setPageMargin(-80);
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                if ((position == mAdapter.getCount() - 1) && !isLastPage && !isUpdate) {
                    //到最后一页自动加载更多
                    getCards();
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        ImageButton backImageButton = (ImageButton) findViewById(R.id.browse_back_imageButton);
        backImageButton.setOnClickListener(this);

    }

    @Override
    public void updateCard(List<CardAndUserVO> cards) {
        if (cards != null) {
            if (cards.size() < Constant.CARD_NUM_OF_ONEPAGE) {
                isLastPage = true;
            } else {
                mCurrentPage++;
            }
            for (CardAndUserVO card : cards) {
                BrowseFragment bf = new BrowseFragment();
                bf.setCard(card);
                mBrowseFragmentList.add(bf);
            }
            mAdapter.notifyDataSetChanged(true);
        } else {
            isLastPage = true;
        }
        isUpdate = false;
    }

    @Override
    public void enterCardDetail(CardVO card) {
        Intent intent = new Intent(BrowseActivity.this, BrowseDetailActivity.class);
        intent.putExtra("card", card);
        startActivityForResult(intent, 1);
    }

    @Override
    public void enterOtherHomepage(UserVO user) {
        if (user.getUserId() == MyApplication.getUser().getUserId()) {
            Intent intent = new Intent(this, PersonalHomepageActivity.class);
            startActivity(intent);
        } else {
            Intent intent = new Intent(BrowseActivity.this, OtherHomepageActivity.class);
            intent.putExtra("user", user);
            startActivity(intent);
        }
    }

    @Override
    public void subscribe(int subscribeId, int userId) {
        mPresenter.subscribe(subscribeId, userId);
    }

    @Override
    public void subscribeError(int subscribeId, String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
        for (BrowseFragment browseFragment : mBrowseFragmentList) {
            if (browseFragment.getCard().getUserVO().getUserId() == subscribeId) {
                boolean b = browseFragment.getCard().getUserVO().getSubsribeStatus();
                browseFragment.getCard().getUserVO().setSubsribeStatus(!b);
                mAdapter.notifyDataSetChanged(true);
                return;
            }
        }
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.browse_back_imageButton:
                onBackPressed();
                break;

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mPresenter.clearDisposable();
    }

    @Override
    public BrowsePresenter getInstance() {
        return new BrowsePresenter();
    }

    @Override
    public void onBackPressed() {
        if (JZVideoPlayer.backPress()) {
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void onPause() {
        super.onPause();
        JZVideoPlayer.releaseAllVideos();
    }

}

